/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React from 'react';
import { observer } from 'mobx-react';
import { Modal, Form, Input, Select, Col, Button, Checkbox, message } from 'antd';
import { http } from 'libs';
import store from './store';
import TemplateSelector from "./TemplateSelector";
import {ACEditor} from "../../../components";

@observer
class ComForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      uploading: false,
      password: null,
      addZone: null,
      fileList: [],
      editZone: store.record.zone,
      body: '',
      template_content: '',
      checked: false,
    };
  }

  handleSubmit = () => {
    this.setState({loading: true});
    const formData = this.props.form.getFieldsValue();
    formData['id'] = store.record.id;
    formData['content'] = this.state.body
    formData['checked'] = this.state.checked
    formData['template'] = this.state.template_content
    http.post('/api/message/push/', formData)
      .then(res => {
        if (res === 'auth fail') {
          if (formData.pkey) {
            message.error('独立密钥认证失败')
          } else {
            this.setState({loading: false});
            Modal.confirm({
              icon: 'exclamation-circle',
              title: '首次验证请输入密码',
              content: this.confirmForm(formData.username),
              onOk: () => this.handleConfirm(formData),
            })
          }
        } else {
          message.success('操作成功');
          store.formVisible = false;
          store.fetchRecords()
        }
      }, () => this.setState({loading: false}))
  };

  render() {
    const info = store.record;
    const {body, template_content, loading} = this.state;
    const {getFieldDecorator} = this.props.form;
    return (
      <Modal
        visible
        width={800}
        maskClosable={false}
        title={store.record.id ? '编辑消息推送' : '新建消息推送'}
        okText="提交"
        onCancel={() => store.formVisible = false}
        confirmLoading={loading}
        onOk={this.handleSubmit}>
        <Form labelCol={{span: 6}} wrapperCol={{span: 14}}>
          <Form.Item required label="消息服务">
            <Col span={14}>
              {getFieldDecorator('messageservice_id', {initialValue: info['messageservice_id']})(
                <Select allowClear placeholder="请选择" onChange={v => store.messageservice_id = v}>
                  {store.messageservices.map(item => (
                    <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                  ))}
                </Select>
              )}
            </Col>
          </Form.Item>
          <Form.Item required label="@人员列表">
            {getFieldDecorator('mentioned_list', {initialValue: info['mentioned_list']})(
              <Select mode="multiple" allowClear placeholder="请选择">
                  {store.messageusers.map(item => (
                    <Select.Option value={item.userid} key={item.userid}>{item.name}</Select.Option>
                  ))}
                </Select>
            )}
          </Form.Item>
          <Form.Item label="消息正文">
            <ACEditor mode="sh" value={body} height="80px" onChange={body => this.setState({body})}/>
          </Form.Item>
          <Form.Item label="是否使用模板">
            <Checkbox onChange={checked => this.setState({checked: !this.state.checked, template_content: ""})}/>
          </Form.Item>
          {this.state.checked &&
          <Form.Item label="模板内容">
            <ACEditor readOnly="true" mode="python" value={template_content} height="100px" onChange={template_content => this.setState({template_content})}/>
            <Button icon="plus" onClick={store.switchTemplate}>从执行模版中选择</Button>
          </Form.Item>}
          <Form.Item label="备注信息">
            {getFieldDecorator('desc', {initialValue: info['desc']})(
              <Input.TextArea placeholder="请输入备注信息"/>
            )}
          </Form.Item>
          <Form.Item wrapperCol={{span: 14, offset: 6}}>
            <span role="img" aria-label="notice">⚠️ 消息推送影响较大，请谨慎使用。</span>
          </Form.Item>
          {store.showTemplate && <TemplateSelector onCancel={store.switchTemplate} onOk={v => this.setState({template_content: template_content + v})}/>}
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(ComForm)
